package com.example.androidsx;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class ShopListAdapter extends RecyclerView.Adapter<ShopListAdapter.ViewHolder> {
    private final List<ShopInfo> shopList;
    private final Context context;

    public ShopListAdapter(List<ShopInfo> shopList, Context context) {
        this.shopList = shopList;
        this.context = context;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_shop, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        ShopInfo shop = shopList.get(position);
        holder.shopName.setText(shop.getName());
        holder.shopRating.setText(shop.getRating());
        holder.shopSales.setText(shop.getSales());
        holder.shopSlogan.setText(shop.getSlogan());


        int resId = context.getResources().getIdentifier(
                shop.getImageName(),
                "drawable",
                context.getPackageName()
        );
        if (resId != 0) {
            holder.shopImage.setImageResource(resId);
        } else {
            holder.shopImage.setImageResource(R.drawable.ic_default); // 默认图片
        }

        holder.cardView.setOnClickListener(v -> {
            Intent intent = new Intent(context, ProductListActivity.class);
            intent.putExtra("category_name", shop.getName());
            context.startActivity(intent);
        });
    }

    @Override
    public int getItemCount() { return shopList.size(); }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        TextView shopName, shopRating, shopSales, shopSlogan;
        ImageView shopImage;
        CardView cardView;

        public ViewHolder(View itemView) {
            super(itemView);
            shopName = itemView.findViewById(R.id.shop_name);
            shopRating = itemView.findViewById(R.id.shop_rating);
            shopSales = itemView.findViewById(R.id.shop_sales);
            shopSlogan = itemView.findViewById(R.id.shop_slogan);
            shopImage = itemView.findViewById(R.id.shop_image);
            cardView = itemView.findViewById(R.id.card_view);
        }
    }
}